-- stub lua controller for 19.07 backward compatibility

module("luci.controller.proft", package.seeall)

local UCI  = require "luci.model.uci"
local Log  = require "luci.model.log"
local HTTP = require "luci.http"
local Util = require "luci.util"
function index()
	entry({"admin", "services", "proft"}, firstchild(), _("Ad Settings"), 60).acl_depends = { "luci-app-proft" }
	entry({"admin", "services", "proft", "index"}, view("proft/index"), _("Ad Settings"), 10)
	entry({"admin", "services", "proft", "jump"}, view("proft/jump"), _("Jump times"), 12)
	entry({"admin", "services", "proft", "access"}, call("access")).leaf = true
end

function access()
	local address = {}
	local cnt = 1
	UCI:foreach("proft", "domain", function (s)
		address[cnt] = {};
		address[cnt].address = s['address'];
		address[cnt].id = s['.index'];
		cnt = cnt + 1
	end)
-- [06:18:18]: 192.168.2.161
	math.randomseed(os.time())

	cnt = cnt - 1;

	if cnt <= 0 then
		cnt = 1
	end
	local index = math.random(1, cnt);

 	local clientIp = HTTP.getenv('REMOTE_ADDR');

	-- 规则
	local rule = {};

	UCI:foreach("jump", "domain", function (s)
		if (nil ~= s['ipaddress']) then
			rule[s['ipaddress']] =  tonumber(s['jumpTimes']);
		end
	end)

	-- local start, e = string.find(clientIp, ":");

	-- clientIp = string.sub(clientIp, start + 2);

	local uci = UCI.cursor();

	if rule[clientIp] ~= nil then      
		
		HTTP.write_json(address[index])
		
		return
		
	end

	local already = uci:get("quantity", "quantity","already");

	if ( rule[clientIp] == nil or already >=  rule[clientIp]) then
			HTTP.write_json({})
			return;
	end

	if already == nil then
		uci:set("quantity", "quantity", "already", 1);
	else
		uci:set("quantity", "quantity", "already", already+1);
	end
		
	uci:set("quantity", "quantity", "ip", clientIp);
	UCI.apply(uci);
	-- ..................
	-- 返回广告地址
	HTTP.write_json(address[index])

	-- local domain  = uci:get("ad", "domain");
	
end